package com.ipzoe.app.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ipzoe.act.domain.Activity;
import com.ipzoe.act.domain.ActivitySignup;
import com.ipzoe.act.service.IActivityService;
import com.ipzoe.act.service.IActivitySignupService;
import com.ipzoe.app.convert.ActivityConvert;
import com.ipzoe.app.core.annotation.Login;
import com.ipzoe.app.core.annotation.LoginUser;
import com.ipzoe.app.core.constants.AppConstants;
import com.ipzoe.app.dto.ActivityDTO;
import com.ipzoe.app.dto.ActivityQueryDTO;
import com.ipzoe.app.dto.ActivityResponseDTO;
import com.ipzoe.app.dto.ActivitySignupDTO;
import com.ipzoe.common.core.controller.BaseController;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.core.page.TableDataInfo;
import com.ipzoe.common.exception.CustomException;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.system.service.IRegionService;
import com.ipzoe.system.service.ISysDictDataService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 活动Controller
 * 
 * @author lcl
 * @date 2020-08-29
 */
@RestController
@RequestMapping("api/v1/cms/activity")
@Api(tags = "活动相关")
@Validated
@Slf4j
public class ActivityController extends BaseController
{

    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private IRegionService iRegionService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private IActivitySignupService iActivitySignupService;

    /**
     * 查询活动列表
     * 搜索条件：<br>
     * <p>
     *     tp=1 今天  tp=2 明天 tp=3 本周 tp=4本月<br>
     *     cp=1 城市<br>
     *     sp=1 状态<br>
     *     pp=1 类型
     *     pg=1 分页
     * </p>
     */
    @PostMapping("/list")
    @ApiOperation("查询活动列表")
    public AjaxResult list(@RequestBody ActivityQueryDTO query)
    {
        int pageSize = 10;
        Long cp = query.getCp();
        Integer pg = query.getPg();
        if(pg==null){
            pg = 1;
        }
        String pp = query.getPp();
        String sp = query.getSp();
        String tp = query.getTp();

        LambdaQueryWrapper<Activity> activityLqw = new LambdaQueryWrapper<>();
        activityLqw.eq(StrUtil.isNotBlank(pp) ,Activity::getPermission, pp);
        activityLqw.eq(StrUtil.isNotBlank(sp), Activity::getStatus, sp);
        activityLqw.eq(cp != null, Activity::getCityCode, cp);
        activityLqw.apply("1".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({0},'%y%m%d') ", DateUtil.today());
        activityLqw.apply("2".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({0},'%y%m%d') ", DateUtil.tomorrow().toString());
        activityLqw.apply("3".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({1},'%y%m%d') ", DateUtil.endOfWeek(new Date()).toString(), DateUtil.beginOfWeek(new Date()).toString());
        activityLqw.apply("4".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({1},'%y%m%d') ", DateUtil.endOfMonth(new Date()).toString(), DateUtil.beginOfMonth(new Date()).toString());
        activityLqw.orderByDesc(Activity::getId);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Activity> page = iActivityService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pg, pageSize), activityLqw);
        Page<ActivityDTO> dtoPage = ActivityConvert.INSTANCE.convert(page);
        dtoPage.getRecords().forEach(r->{
            r.setCity(iRegionService.getById(r.getCityCode()));
            r.setPermissionDictLabel(iSysDictDataService.selectDictLabel("act_active_permission", String.valueOf(r.getPermission())));
            r.setStatusDictLabel(iSysDictDataService.selectDictLabel("act_active_status", String.valueOf(r.getStatus())));
        });
        return AjaxResult.success(dtoPage);
    }

    /**
     * 查询活动列表
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("查询活动详情")
    public AjaxResult detail(@PathVariable Long id,HttpServletRequest request)
    {
        Activity activity = iActivityService.getById(id);
        if(activity != null){
            activity.setPvNum(activity.getPvNum()+1);
            iActivityService.updateById(activity);

            ActivityDTO activityDTO = ActivityConvert.INSTANCE.convert(activity);
            activityDTO.setCity(iRegionService.getById(activityDTO.getCityCode()));
            activityDTO.setPermissionDictLabel(iSysDictDataService.selectDictLabel("act_active_permission", String.valueOf(activityDTO.getPermission())));
            activityDTO.setStatusDictLabel(iSysDictDataService.selectDictLabel("act_active_status", String.valueOf(activityDTO.getStatus())));
            activityDTO.setSignable(false);
            if(ObjectUtil.isNotNull(request.getAttribute(AppConstants.REQUEST_ATTRIBUTE_KEY_MEMBER))){
                Member member = (Member) request.getAttribute(AppConstants.REQUEST_ATTRIBUTE_KEY_MEMBER);
                LambdaQueryWrapper<ActivitySignup> activitySignupLqw = new LambdaQueryWrapper<>();
                activitySignupLqw.eq(ActivitySignup::getActivityId, id).eq(ActivitySignup::getMemberId, member.getId());
                if(iActivitySignupService.count(activitySignupLqw)>0)
                {
                    activityDTO.setSignable(true);
                }
            }

            return AjaxResult.success(activityDTO);
        }

        return AjaxResult.success(null);
    }

    @Login
    @ApiOperation("报名")
    @PostMapping("/signUp")
    public AjaxResult signUp(@Validated @RequestBody ActivitySignupDTO activitySignupDTO, HttpServletRequest request){

        if(!Validator.isMobile(activitySignupDTO.getMobile())){
            throw new CustomException(400,"请输入正确的手机号码");
        }
        if(!Validator.isEmail(activitySignupDTO.getEmail())){
            throw new CustomException(400,"请输入正确的邮箱");
        }
        Member member = (Member) request.getAttribute(AppConstants.REQUEST_ATTRIBUTE_KEY_MEMBER);
        iActivityService.signUp(activitySignupDTO.getActivityId(),
                activitySignupDTO.getUsername(), activitySignupDTO.getNickname(),
                activitySignupDTO.getMobile(), activitySignupDTO.getEmail(), member);

        return AjaxResult.success();
    }

}
